package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-28
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService
{
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询报警数据
     * 
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     * 
     * @param alertData 报警数据
     * @return 报警数据
     */

    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData)
    {
        // 获取当前登录用户ID
        Long currentUserId = SecurityUtils.getUserId();
        // 如果不是超级管理员，则只查询当前用户的数据
        if (!SecurityUtils.isAdmin(currentUserId)) {
            alertData.setUserId(currentUserId);
        }
        // 查询报警数据列表
        List<AlertData> alertDataList = alertDataMapper.selectAlertDataList(alertData);
        // 获取处理用户的名称
        for (AlertData data : alertDataList) {
            SysUser sysUser = sysUserMapper.selectUserById(data.getProcessorId());
            if (sysUser!= null) {
                data.setProcessorName(sysUser.getUserName());
            }
        }
        return alertDataList;
    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData)
    {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 处理报警数据
     *
     * @param dto
     */
    @Override
    public void handleAlertData(AlertDataDto dto) {
        //时间转换
        LocalDateTime processingTime = OffsetDateTime.parse(dto.getProcessingTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //查询当前记录，获取 iotId 和 alertRuleId
        AlertData current = alertDataMapper.selectById(dto.getId());
        // 查找相同iotId和alertRuleId和时间相同的且未处理的报警数据
        List<AlertData> unprocessedAlerts = this.lambdaQuery()
                .eq(AlertData::getIotId, current.getIotId())
                .eq(AlertData::getAlertRuleId, current.getAlertRuleId())
                .eq(AlertData::getStatus, 0)
                .eq(AlertData::getCreateTime, current.getCreateTime())
                .list();
        //循环处理
        for (AlertData alert : unprocessedAlerts) {
            AlertData update = new AlertData();
            update.setId(alert.getId());
            update.setProcessingResult(dto.getProcessingResult());
            update.setProcessingTime(processingTime);
            update.setProcessorId(SecurityUtils.getUserId());
            update.setProcessorName(SecurityUtils.getUsername());
            update.setStatus(1);
            alertDataMapper.handleAlertData(update);
        }
    }


}
